// 自定义JavaScript功能

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 Streamlit应用已加载');
    
    // 添加页面加载动画
    addLoadingAnimation();
    
    // 初始化工具提示
    initTooltips();
    
    // 添加键盘快捷键
    addKeyboardShortcuts();
    
    // 优化图表显示
    optimizeCharts();
    
    // 添加页面统计
    trackPageView();
});

// 添加加载动画
function addLoadingAnimation() {
    const elements = document.querySelectorAll('.main .block-container > *');
    elements.forEach((element, index) => {
        element.style.opacity = '0';
        element.style.transform = 'translateY(30px)';
        element.style.transition = 'all 0.6s ease-out';
        
        setTimeout(() => {
            element.style.opacity = '1';
            element.style.transform = 'translateY(0)';
        }, index * 100);
    });
}

// 初始化工具提示
function initTooltips() {
    // 为带有title属性的元素添加自定义工具提示
    const elementsWithTitle = document.querySelectorAll('[title]');
    elementsWithTitle.forEach(element => {
        const title = element.getAttribute('title');
        if (title) {
            element.classList.add('tooltip');
            element.removeAttribute('title');
            
            const tooltipText = document.createElement('span');
            tooltipText.className = 'tooltiptext';
            tooltipText.textContent = title;
            element.appendChild(tooltipText);
        }
    });
}

// 添加键盘快捷键
function addKeyboardShortcuts() {
    document.addEventListener('keydown', function(e) {
        // Ctrl+/ 显示快捷键帮助
        if (e.ctrlKey && e.key === '/') {
            e.preventDefault();
            showKeyboardShortcuts();
        }
        
        // Ctrl+1-5 快速导航到不同页面
        if (e.ctrlKey && e.key >= '1' && e.key <= '5') {
            e.preventDefault();
            const pageIndex = parseInt(e.key) - 1;
            navigateToPage(pageIndex);
        }
        
        // ESC 关闭模态框
        if (e.key === 'Escape') {
            closeModals();
        }
        
        // F11 全屏切换
        if (e.key === 'F11') {
            e.preventDefault();
            toggleFullscreen();
        }
    });
}

// 显示快捷键帮助
function showKeyboardShortcuts() {
    const shortcuts = [
        'Ctrl + 1-5: 快速导航页面',
        'Ctrl + /: 显示快捷键帮助',
        'ESC: 关闭模态框',
        'F11: 全屏切换'
    ];
    
    alert('⌨️ 键盘快捷键:\n\n' + shortcuts.join('\n'));
}

// 页面导航
function navigateToPage(pageIndex) {
    const navButtons = document.querySelectorAll('.stTabs [data-baseweb="tab"]');
    if (navButtons[pageIndex]) {
        navButtons[pageIndex].click();
    }
}

// 关闭模态框
function closeModals() {
    const modals = document.querySelectorAll('.stModal');
    modals.forEach(modal => {
        modal.style.display = 'none';
    });
}

// 全屏切换
function toggleFullscreen() {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen();
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
    }
}

// 优化图表显示
function optimizeCharts() {
    // 监听窗口大小变化，重新调整图表
    window.addEventListener('resize', debounce(function() {
        const charts = document.querySelectorAll('.js-plotly-plot');
        charts.forEach(chart => {
            if (window.Plotly) {
                window.Plotly.Plots.resize(chart);
            }
        });
    }, 300));
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 页面访问统计
function trackPageView() {
    // 记录页面访问时间
    const startTime = Date.now();
    
    // 页面卸载时记录停留时间
    window.addEventListener('beforeunload', function() {
        const duration = Date.now() - startTime;
        console.log(`📊 页面停留时间: ${Math.round(duration / 1000)}秒`);
        
        // 这里可以发送统计数据到后端
        // sendAnalytics('page_view_duration', duration);
    });
}

// 平滑滚动
function smoothScrollTo(elementId) {
    const element = document.getElementById(elementId);
    if (element) {
        element.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
}

// 添加滚动效果
function addScrollEffects() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-fade-in-up');
            }
        });
    }, observerOptions);
    
    // 观察所有卡片元素
    const cards = document.querySelectorAll('.card, .metric-container');
    cards.forEach(card => {
        observer.observe(card);
    });
}

// 主题切换
function toggleTheme() {
    const body = document.body;
    const isDark = body.classList.contains('dark-theme');
    
    if (isDark) {
        body.classList.remove('dark-theme');
        localStorage.setItem('theme', 'light');
    } else {
        body.classList.add('dark-theme');
        localStorage.setItem('theme', 'dark');
    }
    
    // 更新图表主题
    updateChartsTheme(!isDark);
}

// 更新图表主题
function updateChartsTheme(isDark) {
    const charts = document.querySelectorAll('.js-plotly-plot');
    charts.forEach(chart => {
        if (window.Plotly) {
            const update = {
                'paper_bgcolor': isDark ? '#2c3e50' : '#ffffff',
                'plot_bgcolor': isDark ? '#34495e' : '#f8f9fa',
                'font.color': isDark ? '#ecf0f1' : '#2c3e50'
            };
            
            window.Plotly.relayout(chart, update);
        }
    });
}

// 初始化主题
function initTheme() {
    const savedTheme = localStorage.getItem('theme');
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    
    if (savedTheme === 'dark' || (!savedTheme && prefersDark)) {
        document.body.classList.add('dark-theme');
    }
}

// 添加返回顶部按钮
function addBackToTopButton() {
    const button = document.createElement('button');
    button.innerHTML = '↑';
    button.className = 'back-to-top';
    button.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: linear-gradient(45deg, #3498db, #2980b9);
        color: white;
        border: none;
        font-size: 20px;
        cursor: pointer;
        display: none;
        z-index: 1000;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
    `;
    
    button.addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
    
    // 监听滚动事件
    window.addEventListener('scroll', () => {
        if (window.pageYOffset > 300) {
            button.style.display = 'block';
        } else {
            button.style.display = 'none';
        }
    });
    
    document.body.appendChild(button);
}

// 页面性能监控
function monitorPerformance() {
    if ('performance' in window) {
        window.addEventListener('load', () => {
            setTimeout(() => {
                const perfData = performance.getEntriesByType('navigation')[0];
                const loadTime = perfData.loadEventEnd - perfData.loadEventStart;
                
                console.log(`⚡ 页面加载时间: ${loadTime}ms`);
                
                // 如果加载时间过长，显示提示
                if (loadTime > 3000) {
                    console.warn('⚠️ 页面加载较慢，建议优化');
                }
            }, 0);
        });
    }
}

// 错误处理
window.addEventListener('error', function(e) {
    console.error('❌ JavaScript错误:', e.error);
    
    // 可以发送错误报告到后端
    // sendErrorReport(e.error);
});

// 初始化所有功能
function initializeApp() {
    initTheme();
    addScrollEffects();
    addBackToTopButton();
    monitorPerformance();
    
    console.log('✅ 所有JavaScript功能已初始化');
}

// 页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeApp);
} else {
    initializeApp();
}
